import axios from './index';

export const post = (url, params, extra = {}) => {
  const {authCallback, authCancelCallback} = extra;

  return axios({
    url,
    method: 'POST',
    headers: {
      'Content-type': 'application/json; charset=UTF-8'
    },
    data: params,
    ...extra
  })
    .then(res => {
      if (res.data) {
        if (authCallback) {
          authCallback();
        }
        if (authCancelCallback) {
          authCancelCallback();
        }
      }
      return res;
    })
    .catch(err => {
      if (axios._axios.isCancel(err)) {
        throw new Error('cancel');
      } else {
        // eslint-disable-next-line no-console
        console.error(err);
        // handle error
      }
    });
};

export const get = (url, params = {}, extra = {}) => {
  const {authCallback, authCancelCallback} = extra;

  return axios
    .get(url, {
      data: params,
      ...extra
    })
    .then(res => {
      if (res.data) {
        if (authCallback) {
          authCallback();
        }
        if (authCancelCallback) {
          authCancelCallback();
        }
      }
      return res;
    })
    .catch(thrown => {
      if (axios._axios.isCancel(thrown)) {
        throw new Error('cancel');
      } else {
        // eslint-disable-next-line no-console
        console.error(thrown);
        // handle error
      }
    });
};

// preFileName表示默认文件名前缀
export const download = (url, params = {}, extra = {}) => {
  // 兼容get请求下载的形式
  const {preFileName = '', noLoading, loadingText, method} = extra;
  let cancel;
  // 如果没有传入用户自定义的Loading处理状态
  if (!noLoading) {
    cancel = alert(loadingText || '正在处理...');
  }
  return axios(
    {
      method: method || 'post',
      responseType: 'blob',
      url,
      headers: {
        'Content-type': 'application/json; charset =UTF-8'
      },
      data: params
    }
  )
    .then(res => {
      cancel && cancel();
      const blob = res.data;
      const fileName = preFileName + res.headers?.['file_name'];
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      return res;
    })
    .catch(thrown => {
      cancel && cancel();
      alert('操作失败')
      return thrown
    });
}